package com.snowruin.distributed.lock.common.utils;

import java.lang.reflect.Method;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * spel 表达式 处理工具
 * @author zxm
 * @date   2019年3月14日
 * @url    https://www.snowruin.com
 *
 */
public class SPELUtils {

	private SPELUtils () {}
	
	private static ExpressionParser expressionParser = new SpelExpressionParser();
	
	private static LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();

	/**
	 * 解析 表达式
	 * @param keyName
	 * @param method
	 * @param args
	 * @return
	 */
	public static String parser(String keyName, Method method , Object [] args) {
		String[] parameterNames = localVariableTableParameterNameDiscoverer.getParameterNames(method);
		EvaluationContext evaluationContext = new StandardEvaluationContext();
		
		int index = 0;
		for (String param : parameterNames) {
			evaluationContext.setVariable(param, args[index]);
			index ++;
		}
		return expressionParser.parseExpression(keyName).getValue(evaluationContext, String.class);
	}
	
}
